import os
import urllib

class DirectoryTreeDictionary:
    def __init__(self, rootDirectory):
        self.rootDirectory = os.path.abspath(rootDirectory)
        #pr "root directory is", self.rootDirectory
    def __getitem__(self, path):
        #pr "getting info dict for", repr(path)
        assert path.find("..")<0, "relative paths are not permitted"
        while path.startswith("/"):
            path = path[1:]
        rootDirectory = self.rootDirectory
        fullpath = os.path.join(rootDirectory, path)
        #pr "full path for", path, "is", fullpath
        if not os.path.exists(fullpath):
            raise KeyError, "no such file "+repr(path)
        D = {}
        parent = children = None
        (parent, dummy) = os.path.split(path)
        if parent==path or not parent:
            parent = None
        try:
            if os.path.isdir(fullpath):
                listing = os.listdir(fullpath)
                nlisting = len(listing)
                body = "%s: dir with %s entries" % (path, nlisting)
                children = [ os.path.join(path, p) for p in listing ]
                #pr "for", (path, fullpath), "children are", children
            elif os.path.isfile(fullpath):
                size = os.path.getsize(fullpath)
                anchor = "getContent?path=%s" % (urllib.quote(path))
                link = '<a href="%s">%s</a>' % (anchor, path)
                body = "%s: file of size %s" % (link, size)
        except OSError:
            body = "%s: protected file" % path
        D["body"] = body
        if parent:
            D["parent"] = parent
        if children:
            D["children"] = children
        #pr "returning info dict", (path, D)
        return D
